/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package adbus.libraries;

import adbus.models.Table;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rafal
 */
public abstract class ORM {

    protected ResultSet result = null;
    protected LinkedHashMap<String, String> filters = new LinkedHashMap();
    protected LinkedHashMap<String, Object> filtersval = new LinkedHashMap();

    abstract public String basicQuery();

    public void zaladuj() {
        try {
            result = Database.querySelect(basicQuery() + getWhere(), filtersval);
            //fireTableDataChanged();
        } catch (SQLException ex) {
            Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected String getWhere() {
        String where = " WHERE ";
        //String col[] = filters.values().toArray(new String[0]);
        if (filters.size() == 0) {
            return "";
        }
        int i = 0;
        for (Map.Entry<String, String> entry : filters.entrySet()) {
            where += entry.getValue();
            if (i < filters.size() - 1) {
                where += " AND ";
            }
            i++;
        }
        return where;
    }

    public void resetFilters() {
        filters.clear();
        filtersval.clear();
        zaladuj();
    }

    public ResultSet zapisz(String q, String id, LinkedHashMap<String, Object> hm) {
        try {
            System.out.println(q);
            ResultSet temp = Database.queryUpdate(q, id, hm);
            temp.first();
            return temp;
        } catch (SQLException ex) {
            Logger.getLogger(ORM.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}
